package com.smallkingson.ylib.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.smallkingson.ylib.R;
import com.smallkingson.ylib.view.utils.YCanvases;

/**
 * Created by yorun on 2017/4/13.
 */

public class YChatImageView extends android.support.v7.widget.AppCompatImageView {
    Paint paint;
    PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    Bitmap dst;
    private final NinePatch patch;

    int mWidth;
    int mHeight;
    public YChatImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, com.smallkingson.ylib.R.styleable.yr);

        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        int resourceId = array.getResourceId(R.styleable.yr_ninePatchRes, 0);
        if (resourceId==0) {
            throw new IllegalArgumentException();
        }
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
        patch = new NinePatch(bitmap, bitmap.getNinePatchChunk(),"");
        array.recycle();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();
        if (drawable==null) {
            return;
        }
        Bitmap src = ((BitmapDrawable) drawable).getBitmap();
        if (src==null) {
            return ;
        }
        int width = src.getWidth();
        int height =src. getHeight();
        if (mWidth!= width ||mHeight!= height||dst==null) {
            dst= Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
            Canvas can = new Canvas(dst);
            patch.draw(can,new Rect(0,0, width, height));
            mWidth=width;
            mHeight = height;
        }
//        int sc = canvas.saveLayer(0, 0, width, height, null,
//                Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG
//                        | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
//                        | Canvas.FULL_COLOR_LAYER_SAVE_FLAG
//                        | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
        YCanvases.draw(canvas, dst, 0, 0, width, height, paint);
        paint.setXfermode(xfermode);
        YCanvases.draw(canvas, src, 0, 0, src.getWidth(),  src.getHeight(), paint);
        paint.setXfermode(null);
//        canvas.restoreToCount(sc);
    }
}
